package com.frkj.yuan.fragment.home.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.frkj.yuan.R;
import com.frkj.yuan.activity.ProtocolActivity;
import com.frkj.yuan.activity.WaitOrderMapActivity;
import com.frkj.yuan.adapter.BaseRecyclerHolder;
import com.frkj.yuan.adapter.BaseRecyclerRefreshAdapter;
import com.frkj.yuan.api.bean.OrderPayorderMsgBean;
import com.frkj.yuan.api.bean.YuyueOrderServiceBean;
import com.frkj.yuan.api.category.YuyueOrderServiceCategory;
import com.frkj.yuan.api.presenter.YuyueOrderServicePresenter;
import com.frkj.yuan.base.BaseActivity;
import com.frkj.yuan.data.YuyueKeshiDataUtils;
import com.frkj.yuan.dialog.SelectYouHuiQuanDialog;
import com.frkj.yuan.dialog.SelectZhifuDialog;
import com.frkj.yuan.fragment.home.PayResult;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.utils.SPUtils;
import com.frkj.yuan.utils.ToastUtil;
import com.frkj.yuan.view.RecyclerViewLayoutManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;

/**
 * 信息说明: 预约下单界面
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/3/29 16 ：19
 * 项目名称：yuanban
 */
public class YuyueOrderActoivity extends BaseActivity implements View.OnClickListener, YuyueOrderServiceCategory.View {
    @BindView(R.id.base_title)
    TextView mTitleMsg;
    @BindView(R.id.pay_zhif)
    TextView mPayZhif;
    @BindView(R.id.order_mobile)
    TextView mOrderMobile;
    @BindView(R.id.order_name)
    TextView mOrderName;
    @BindView(R.id.order_riqi)
    TextView mDateRiqi;
    @BindView(R.id.service_detials)
    TextView mServiceDetials;
    @BindView(R.id.order_card)
    TextView mOrderCard;
    @BindView(R.id.order_yiyuan)
    TextView mOrderYiyuan;
    @BindView(R.id.edit_msg)
    EditText mEditMsg;
    @BindView(R.id.order_price_pay)
    TextView mPayorderPrice;
    @BindView(R.id.check_box)
    CheckBox mCheckBox;
    @BindView(R.id.linear_areed)
    LinearLayout mlinear_areed;
    private RecyclerView mUserRecyclerView, mNoUserRecyclerView;
    private String mPayStates;
    private SelectZhifuDialog mDialog;
    private String mToken;
    private long mUserId;
    private YuyueOrderServicePresenter mPresenter;
    private long mJiuPersonId;
    private String SelectType;
    private String serviceName;
    private int serviceInfoId;
    private int serviceCategoryId;
    private long hospitalId;
    private String hospitalName;
    private String officeName;
    private String selectTime;
    private String keshiId;
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("resultInfo", resultInfo + "===resultStatus==" + resultStatus);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtil.showToastSUCCESS(YuyueOrderActoivity.this, "支付成功");
                        Bundle bundle = new Bundle();
                        bundle.putLong("hospitalId", hospitalId);
                        bundle.putString("hospitalName", hospitalName);
                        bundle.putString("orderId", mOrderId);
                        openActivityWitchAnimation(WaitOrderMapActivity.class, bundle);
                        finish();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtil.showToastINFO(YuyueOrderActoivity.this, "支付结果确认中");
                        } else {
                            ToastUtil.showToastINFO(YuyueOrderActoivity.this, "用户取消支付");
                            finish();
                        }
                    }
                    break;
                }
            }
        }
    };
    private String mJiuPersonName;
    private String mOrderId;
    private String mPrice;

    @Override
    public int getLayoutId() {
        return R.layout.activity_yuyue_order_new_view;
    }

    @Override
    public void initLayoutView() {
        mTitleMsg.setText("确认下单");
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String regEx = "[\\[\\]]";
                Pattern pattern = Pattern.compile(regEx);
                Matcher matcher = pattern.matcher(source.toString());
                Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
                Matcher emojiMatcher = emoji.matcher(source);
                if (matcher.find() || emojiMatcher.find()|| source.equals(" ")|| source.toString().contentEquals("\n")) {
                    ToastUtil.showToastINFO(YuyueOrderActoivity.this,"禁止输入非法字符");
                    return "";
                } else {
                    return null;
                }
            }
        };
        InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(40);
        mEditMsg.setFilters(new InputFilter[]{filter, lengthFilter});
        YCAppBar.setStatusBarColor(YuyueOrderActoivity.this,
                ContextCompat.getColor(YuyueOrderActoivity.this,
                        R.color.base_color));
        mToken = (String) SPUtils.get(YuyueOrderActoivity.this, ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        hospitalId = getIntent().getLongExtra("hospitalId", 0);
        mJiuPersonId = getIntent().getLongExtra("mJiuPersonId", 0);
        keshiId = getIntent().getStringExtra("keshiId");
        mDateRiqi.setText(getIntent().getStringExtra("shijian"));
        mJiuPersonName = getIntent().getStringExtra("name");
        mOrderName.setText(getIntent().getStringExtra("name"));
        mOrderMobile.setText(getIntent().getStringExtra("mobile"));
        mOrderCard.setText(getIntent().getStringExtra("sfzhm"));
        SelectType = getIntent().getStringExtra("SelectType");
        hospitalName = getIntent().getStringExtra("yiyuan");
        officeName = getIntent().getStringExtra("keshi");
        selectTime = getIntent().getStringExtra("selectTime");
        mOrderYiyuan.setText(getIntent().getStringExtra("yiyuan") + "---" + getIntent().getStringExtra("keshi"));
        mPresenter = new YuyueOrderServicePresenter(this);
        SetPersenter(mPresenter);
        mPresenter.getYuyueOrderService(mToken, 620100, mJiuPersonId, getIntent().getStringExtra("keshi"));
    }
    @OnClick({R.id.base_back, R.id.serice_xieyi, R.id.rel_youhui, R.id.rele_zhifu, R.id.service_detials, R.id.submit_pay_order})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.base_back:
                finishWitchAnimation();
                break;
            case R.id.serice_xieyi:
                Bundle bundle = new Bundle();
                bundle.putString("xieyi", "2");
                openActivityWitchAnimation(ProtocolActivity.class, bundle);
                break;
            case R.id.rel_youhui:
                SelectYouhuiQuan();
                break;
            case R.id.rele_zhifu:
//                SelectZhifuDialog();
                break;
            case R.id.service_detials:
//                openActivityWitchAnimation(YuyueOrderServiceDetialsActivity.class);
                break;
            case R.id.submit_pay_order:
//                openActivityWitchAnimation(SubmitPayOrderActivity.class);
//                openActivityWitchAnimation(PayOrderSuucessActivity.class);
                if (mCheckBox.isChecked() == false) {
                    mlinear_areed.startAnimation(AnimationUtils.loadAnimation(this, R.anim.transla_checkbox));
                    return;
                } else {
                    JSONObject result = new JSONObject();
                    try {
                        result.put("serviceCategoryId", serviceCategoryId);
                        result.put("serviceInfoId", serviceInfoId);
                        result.put("serviceName", serviceName);
                        result.put("patientId", mJiuPersonId);
                        result.put("userId", mUserId);
                        result.put("hospitalId", hospitalId);
                        result.put("hospitalName", hospitalName);
                        result.put("officeId", keshiId);
                        result.put("patientName", mJiuPersonName);
                        result.put("officeName", officeName);
                        result.put("periodType", SelectType);
                        result.put("serviceDay", selectTime);
                        result.put("remark", mEditMsg.getText().toString().trim());
                        result.put("payMethod", 2);
                        result.put("price", mPrice);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mPresenter.getOrderMsg(mToken, result.toString());
                }
                break;
        }
    }

    private void SelectZhifuDialog() {
        mDialog = new SelectZhifuDialog(YuyueOrderActoivity.this);
        mDialog.show();
        mPayStates = "微信支付";
        mDialog.findViewById(R.id.rad_weixin).setOnClickListener(this);
        mDialog.findViewById(R.id.rad_zhifubao).setOnClickListener(this);
        mDialog.findViewById(R.id.rad_yinlian).setOnClickListener(this);
        mDialog.findViewById(R.id.rad_yue).setOnClickListener(this);
        mDialog.findViewById(R.id.commmit_zhfu).setOnClickListener(this);
        mDialog.findViewById(R.id.cancle_zhifu).setOnClickListener(this);
    }

    private void SelectYouhuiQuan() {
        SelectYouHuiQuanDialog dialog = new SelectYouHuiQuanDialog(YuyueOrderActoivity.this);
        dialog.show();
        mUserRecyclerView = (RecyclerView) dialog.findViewById(R.id.use_recyclerVeiw);
        mNoUserRecyclerView = (RecyclerView) dialog.findViewById(R.id.no_recycler);
        RecyclerViewLayoutManager.setLinearVerticalManager(YuyueOrderActoivity.this, mUserRecyclerView);
        RecyclerViewLayoutManager.setLinearVerticalManager(YuyueOrderActoivity.this, mNoUserRecyclerView);
        List<String> mLeftList = YuyueKeshiDataUtils.mUserYou();
        List<String> mRightList = YuyueKeshiDataUtils.mNoser();
        BaseRecyclerRefreshAdapter mUserAdapter = new BaseRecyclerRefreshAdapter<String>(YuyueOrderActoivity.this, mLeftList, R.layout.user_youhui_item) {
            @Override
            public void convert(BaseRecyclerHolder holder, String item, int position, boolean isScrolling) throws IOException {

            }
        };
        mUserRecyclerView.setAdapter(mUserAdapter);
        mUserAdapter.setOnItemClickListener(new BaseRecyclerRefreshAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                dialog.dismiss();
            }
        });
        BaseRecyclerRefreshAdapter mNoAdapter = new BaseRecyclerRefreshAdapter<String>(YuyueOrderActoivity.this, mRightList, R.layout.user_youhui_item) {
            @Override
            public void convert(BaseRecyclerHolder holder, String item, int position, boolean isScrolling) throws IOException {
                holder.getView(R.id.linar_user).setBackgroundResource(R.drawable.no_user_bg);
            }
        };
        mNoUserRecyclerView.setAdapter(mNoAdapter);
        mNoAdapter.setOnItemClickListener(new BaseRecyclerRefreshAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.commmit_zhfu:
                mPayZhif.setText(mPayStates);
                mDialog.dismiss();
                break;
            case R.id.cancle_zhifu:
                mDialog.dismiss();
                break;
            case R.id.rad_weixin:
                mPayStates = "微信支付";
                break;
            case R.id.rad_zhifubao:
                mPayStates = "支付宝支付";
                break;
            case R.id.rad_yue:
                mPayStates = "余额支付";
                break;
            case R.id.rad_yinlian:
                mPayStates = "银联支付";
                break;
        }
    }
    @Override
    public void getYuyueOrderService(YuyueOrderServiceBean yuyueOrder) {
        if (yuyueOrder.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            DecimalFormat format = new DecimalFormat("0.00");
            // TODO: 2022/6/17 当状态为1代表早上时间、2代表下午时间、3代表全天时间
            if (SelectType != null) {
                if (SelectType.equals("1")) {
                    mPrice = format.format(yuyueOrder.getData().getMorningPrice());
                } else if (SelectType.equals("2")) {
                    mPrice = format.format(yuyueOrder.getData().getAfternoonPrice()) ;
                } else if (SelectType.equals("3")) {
                    mPrice = format.format(yuyueOrder.getData().getFulldayPrice());
                }
                mPayorderPrice.setText("￥ " +mPrice);
            }
            serviceName = yuyueOrder.getData().getServiceName();
            mServiceDetials.setText(serviceName);
            serviceInfoId = yuyueOrder.getData().getId();
            serviceCategoryId = yuyueOrder.getData().getCategoryId();
        }
    }

    @Override
    public void getOrderMsg(OrderPayorderMsgBean payorder) {
        if (payorder.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            mOrderId = payorder.getData().getOrderId();
            final Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(YuyueOrderActoivity.this);
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(payorder.getData().getOrderStr(), true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } else {
            ToastUtil.showToastERROR(YuyueOrderActoivity.this, payorder.getMsg());
        }
    }
    @Override
    public void SetPersenter(Object persenter) {}
    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(YuyueOrderActoivity.this, mErrorMsg);
    }
}
